// code-text -> code-preview
// 更新原始内容到预览 - 
function updatePreview() {
    $("#code-preview").html(escapeString($("#code-text").val()))
    // $("#code-preview").html(escapeString($("#editor").text()))
    updatePreviewStyle()
}

// 更新预览行号
function updatePreviewStyle() {
    let code_preview = document.querySelector("#code-preview");
    hljs.highlightElement(code_preview)
    hljs.lineNumbersBlock(code_preview);
    updateCodeLineStyle()
}

function updateCodeLineStyle() {
    setTimeout(() => {
        if ($(".hljs-ln-numbers").length > 0)
        $(".hljs-ln-numbers").each(function (i, item) {
            item.setAttribute("style", "word-break: keep-all;");
        })
        if ($(".hljs-ln-code").length > 0)
        $(".hljs-ln-code").each(function(i ,item){
            item.setAttribute("style", "padding-left: 10px;")
        })
    }, 1);
}
// 全局主题变更
function global_change_theme(theme){
    if (String(theme).startsWith("assets")) {
        let words = String(theme).split('/')
        let _theme = words[words.length-1]
        $("#code-style").attr("href", "assets/highlight.js/styles/" + _theme)
    } else {
        $("#code-style").attr("href", "assets/highlight.js/styles/" + theme)
    }
}

// Pastebin 列表条目元素添加函数
function createPastebin(data, i) {
    let tbody_pastebin = $("#tbody_pastebin");

    // document.createPastebin("th")
    // document.createPastebin("td")

    // id
    let th_id         = document.createElement("th")
    // title
    let td_title      = document.createElement("td")
    // content
    let td_content    = document.createElement("td")
    // author
    let td_author     = document.createElement("td")
    // syntax
    let td_syntax     = document.createElement("td")
    // themes
    let td_themes     = document.createElement("td")
    // tags
    let td_tags       = document.createElement("td")
    // created_at
    let td_created_at = document.createElement("td")
    // uuid
    let td_uuid       = document.createElement("td")
    // operator
    let td_operator   = document.createElement("td")


    let td_operator_button = document.createElement("button")
    td_operator_button.innerHTML = "预览"
    td_operator_button.setAttribute("class", "btn btn-primary")
    td_operator_button.addEventListener("click", function(){
        $.ajax({
            url: "/pastebin/api/show/"+ data[i]["uuid"],
            method: "GET",
            success: function(data){
                $("#modal-show").modal()
                $("#modal-show").attr("pastebin-uuid", data["paste"]["uuid"])
                $("#modal-show").attr("pastebin-content", data["paste"]["content"])
                $("#code-show").html(data["paste"]["content"])
                $("#code-show").attr("class", "language"+data["paste"]["syntax"])
                $("#show-title").html(data["paste"]["title"])
                hljs.highlightElement($("#code-show")[0]);
                hljs.lineNumbersBlock($("#code-show")[0]);
                global_change_theme(data["paste"]["theme"])
                updateCodeLineStyle()
            }
        })
    })
    td_operator.appendChild(td_operator_button)

    th_id        .innerHTML = data[i]["id"];
    td_title     .innerHTML = data[i]["title"];
    td_content   .innerHTML = data[i]["content"];
    td_author    .innerHTML = data[i]["author"];
    td_syntax    .innerHTML = data[i]["syntax"];
    td_themes    .innerHTML = data[i]["themes"];
    td_tags      .innerHTML = data[i]["tags"]
    td_created_at.innerHTML = data[i]["created_at"];
    td_uuid      .innerHTML = data[i]["uuid"];
    
    th_id         .setAttribute("style", "word-break: keep-all; text-align: center;")
    td_tags       .setAttribute("style", "word-break: keep-all; text-align: center;")
    td_tags       .setAttribute("class","hidden-xs")
    td_operator   .setAttribute("style", "text-align: center;")


    let tr = createElement("tr")

    tr.appendChild(th_id        )
    tr.appendChild(td_title     )
    // tr.appendChild(td_content   )
    tr.appendChild(td_author    )
    tr.appendChild(td_tags      )
    // tr.appendChild(td_created_at)
    // tr.appendChild(td_uuid      )
    tr.appendChild(td_operator)

    tbody_pastebin.append(tr)
}


// ---------------------------------------------------------------- 初始化加载
var all = []

function loadPastebinAll() {
    let tbody = document.querySelector("#tbody_pastebin")
    while(tbody.rows.length)
        tbody.deleteRow(0)
    for (let i = 0; i < all.length; i++) {
        createPastebin(all, i)
    }
}

// load Pastebin
function loadPastebin() {
    $.ajax({
        url: "/pastebin/api/all",
        method: "GET",
        success: function(data) {
            all = data
            loadPastebinAll()
        }
    })
}

// load syntax
function loadPastebinSyntax() {
    $.ajax({
        url: "/pastebin/api/syntax",
        method: "GET",
        success: function(data) {
            if (data["status"] != 200) {return}
            
            let opt = $("#opt-syntaxs");
            let syntaxs = data["syntaxs"]

            for (let i = 0; i < syntaxs.length; i++) {
                const element = syntaxs[i];
                let option = document.createElement("option");
                option.value = element["value"]
                option.innerHTML = element["syntax"]
                
                opt.append(option)
            }

            console.log(data["message"])
        }
    })
}

// load themse
function loadPastebinThemes() {
    // load themes
    $.ajax({
        url: "/pastebin/api/themes",
        method: "GET",
        success: function(data) {
            if (data["status"] != 200) {return}
            
            let select = $("#select-themes");
            let themes = data["themes"]

            for (let i = 0; i < themes.length; i++) {
                const element = themes[i];
                let option = document.createElement("option");
                option.value = element["theme"]
                option.innerHTML = element["name"]
                
                select.append(option)
            }

            console.log(data["message"])
        }
    })
}


registerEventHandler(document,'ready', ()=>{
    loadPastebin();
    loadPastebinSyntax();
    loadPastebinThemes();
})


// ---------------------------------------------------------------- 内容处理部分


// 注册 创建-预览-提交事件(标题，内容，作者，语言，主题，标签)
registerEventHandler("#code-submit", 'click', ()=>{
    $.ajax({
        url: "/pastebin/api/create",
        method: "POST",
        data: {
            "title":  $("#input-title").val(),
            "content": escapeString($("#code-text").val()),
            "author": $("#input-author").val(),
            "syntax": $("#select-syntax").val(),
            "themes": $("#select-themes").val(),
            "tags":   $("#input-tags").val(),
        },
        success: function(data, textStatus, jqXHR) {
            if (data["message"] == "success") {
                alert(data["message"]);
                window.location = "/pastebin";
            } else {
                alert(data["message"]);
            }
        }
    })
})

// 注册 代码更新事件
registerEventHandler("#code-update", 'click', ()=>{
    $.ajax({
        url: "/pastebin/api/uuid",
        method: "GET",
        data: {

        }
    })

    $.ajax({
        url: "/pastebin/api/create",
        method: "POST",
        data: {
            "title":  $("#input-title").val(),
            "content": escapeString($("#code-text").val()),
            "author": $("#input-author").val(),
            "syntax": $("#select-syntax").val(),
            "themes": $("#select-themes").val(),
            "tags":   $("#input-tags").val(),
        },
        success: function(data, textStatus, jqXHR) {
            if (data["message"] == "success") {
                alert(data["message"]);
                window.location = "/pastebin";
            } else {
                alert(data["message"]);
            }
        }
    })
})

// ------------------------------------------------------------------------------------------------

// 注册 主题变化处理 - 更改全局主题
registerEventHandler("#select-themes", 'change', function(){
    global_change_theme($(this).val())
})
// 注册 语言变化处理 - 重新渲染内容
registerEventHandler("#select-syntax", 'change', function(){
    $("#code-preview").attr("class","hljs language-"+$(this).val())
    updatePreview()
})

// 注册 创建-预览/准备提交时渲染内容和调整主题
registerEventHandler("#btn-preview", 'click', ()=>{
    updatePreview()
    global_change_theme($("#select-themes").val())
})

// 注册 创建-准备提交事件
registerEventHandler("#btn-ready", 'click', ()=>{
    updatePreview()
    global_change_theme($("#select-themes").val()) 
    // (window.innerHeight - $("#modal-content-preivew > div").height()) /2
})
// 内容改变进行预览更新
$("#code-text").bind("change",function(){
    updatePreview()
})

// 内容搜索处理 - 目前只匹配了 title，需要增加 tags 匹配
$("#title-search").on("input", function(){
    let key = $(this).val().toLowerCase();
    if (key == "") {
        return loadPastebinAll()
    }
    
    let tbody = document.querySelector("#tbody_pastebin")
    while(tbody.rows.length)
        tbody.deleteRow(0)

    valueListKeySearchAfter(key, all, "title", createPastebin)
})

registerEventHandler("#tags-search", 'input', function(){
    let key = $(this).val().toLowerCase();
    if (key == "") {
        return loadPastebinAll()
    }
    
    let tbody = document.querySelector("#tbody_pastebin")
    while(tbody.rows.length)
        tbody.deleteRow(0)

    valueListKeySearchAfter(key, all, "tags", createPastebin)
})

// ------------------------------------------------------------------------------------------------

var TAGS_TO_REPLACE = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    '\'': '&#x27;',
    '\/': '&#x2F;',
    '\\': '&#x5C;'
};
var TAGS_TO_REPLACE_REVERSE = {
    '&amp;': '&',
    '&lt;': '<',
    '&gt;': '>',
    '&quot;': '"',
    '&apos;': '\'',
    '&#x27;': '\'',
    '&#x2F;': '\/',
    '&#x5C;': '\\'
};
var PAGE_TR_TO_REPLACE = {
    '\\\$\$': '$_$_$'
};
var PAGE_TR_TO_REPLACE_REVERSE = {
    '$_$_$': '\\\$\$'
};
function escapePageTrString(params) {
    return params.replace(/\\\$\$/g, function (tag) { return (PAGE_TR_TO_REPLACE[tag] || tag); });
}
function unescapePageTrString(params) {
    return params.replace(/(\$_\$_\$)/g, function (whole) { return (PAGE_TR_TO_REPLACE_REVERSE[whole] || whole); });
}
function escapeString(str) {
    return str.replace(/[&<>"'\/\\]/g, function (tag) { return (TAGS_TO_REPLACE[tag] || tag); });
}
function unescapeString(str) {
    return str.replace(/\&(amp|lt|gt|quot|apos|\#x27|\#x2F|\#x5C)\;/g, function (whole) { return (TAGS_TO_REPLACE_REVERSE[whole] || whole); });
}
